package com.amanda.reggie.service.impl;

import com.amanda.reggie.common.R;
import com.amanda.reggie.entity.Employee;
import com.amanda.reggie.mapper.EmployeeMapper;
import com.amanda.reggie.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author amanda
 * @Description 员工管理业务实现
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     */
    @Override
    public R<Employee> login(HttpServletRequest request, Employee employee) {
        // 1、将页面提交的password进行md5加密处理、
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 2、根据页面提交的username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        String username = employee.getUsername();
        queryWrapper.eq(null != username, Employee::getUsername, username);
        Employee emp = employeeService.getOne(queryWrapper);

        // 3、如果没有查询到则返回登录失败
        if (null == emp) {
            return R.error("没有 "+ username +" 用户，" + "登录失败！");
        }

        // 4、密码比对，不一致就返回登录失败
        if (!emp.getPassword().equals(password)) {
            return R.error("密码错误！");
        }

        // 5、查看员工状态，已禁用则返回“账号已禁用”
        if (0 == emp.getStatus()) {
            return R.error("当前 " + username + " 用户已被禁用！");
        }

        // 6、登录成功，将id存入Session并返回登录成功
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工信息分页查询
     */
    @Override
    public Page<Employee> pageQuery(int page, int pageSize, String name) {
        // 1、构造分页构造器
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        // 2、构造条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 3、填充过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name)
                .or().like(StringUtils.isNotEmpty(name), Employee::getUsername, name);
        // 4、排序
        lambdaQueryWrapper.orderByDesc(Employee::getUpdateTime);
        return employeeService.page(pageInfo, lambdaQueryWrapper);
    }

}
